package com.itheima.health.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MenuService;
import com.itheima.health.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/menu")
@Slf4j
public class MenuController {
    @Autowired
    private MenuService ms;

    @GetMapping("/getUserMenu")
    public Result getUserMenu(HttpServletRequest req) {
        log.info("[获取动态菜单]");
        User user = (User) req.getSession().getAttribute("user");
        Set<Role> roles = user.getRoles();
        //得到数据库中user所对应role的一级menu
        List<Menu> dbL1Menu=new ArrayList<>();
        for (Role role : roles) {
            dbL1Menu = ms.findL1Menu(role.getId());
        }

        //创建符合前端格式的一级菜单
        List<HashMap<String,Object>> l1Map=new ArrayList<>();
        for (Menu menu : dbL1Menu) {
            //创建符合前端格式的二级菜单
            LinkedHashSet<HashMap<String,Object>> l2Map=new LinkedHashSet<>();
            //得到数据库中role对应的此一级menu的二级menu
            List<Menu> dbL2Menu = null;
            for (Role role : roles) {
                dbL2Menu = ms.findL2Menu(role.getId(),menu.getId());
            }
            //整合符合前端格式的二级级菜单
            for (Menu m : dbL2Menu) {
                HashMap<String,Object> map=new HashMap<>();
                map.put("title",m.getName());
                map.put("path",m.getPath());
                map.put("linkUrl",m.getLinkUrl());
                l2Map.add(map);
            }
            //整合符合前端格式的一级菜单
            HashMap<String,Object> map=new HashMap<>();
            map.put("title",menu.getName());
            map.put("path",menu.getPath());
            map.put("icon",menu.getIcon());
            map.put("children",l2Map);
            l1Map.add(map);
        }

        //封装
        HashMap<String,Object> map=new HashMap<>();
        map.put("username",user.getUsername());
        map.put("menuList",l1Map);
        return new Result(true, MessageConst.GET_MENU_SUCCESS,map);
    }
}
